package com.inifitness.sms.config;

import java.time.Duration;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;

import darabonba.core.client.ClientOverrideConfiguration;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 阿里云短信配置
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2023-01-17 09:59
 */
@Configuration
@Log4j2
@Data
@ConditionalOnProperty(value = "sms.type", havingValue = "aliyun")
@ConfigurationProperties(prefix = "sms.config")
public class AliSmsServiceConfig {

  private String accessKeyId;
  private String accessKeySecret;
  private String signName;
  private String successCode;

  private static final Duration CONNECTION_TIMEOUT_SECONDS = Duration.ofSeconds(10);
  private static final Duration RESPONSE_TIMEOUT_SECONDS = Duration.ofSeconds(10);
  private static final Duration MAX_IDLE_TIMEOUT_SECONDS = Duration.ofSeconds(10);
  private static final int MAX_CONNECTIONS = 2<<6;

  @Bean(name = "aliyunHttpClient")
  public HttpClient httpClient() {
    ApacheAsyncHttpClientBuilder httpClientBuilder = new ApacheAsyncHttpClientBuilder()
        .connectionTimeout(CONNECTION_TIMEOUT_SECONDS)
        .responseTimeout(RESPONSE_TIMEOUT_SECONDS)
        .maxConnections(MAX_CONNECTIONS)
        .maxIdleTimeOut(MAX_IDLE_TIMEOUT_SECONDS);
    return httpClientBuilder.build();
  }

  @Bean
  public StaticCredentialProvider staticCredentialProvider() {
    return StaticCredentialProvider.create(Credential.builder()
        .accessKeyId(accessKeyId)
        .accessKeySecret(accessKeySecret)
        .build());
  }

  @Bean
  public ClientOverrideConfiguration clientOverrideConfiguration() {
    return ClientOverrideConfiguration.create()
        .setEndpointOverride("dysmsapi.aliyuncs.com")
        .setConnectTimeout(CONNECTION_TIMEOUT_SECONDS);
  }

  @Bean
  public AsyncClient asyncClient() {
    return AsyncClient.builder()
        .region("cn-qingdao")
        .httpClient(httpClient())
        .credentialsProvider(staticCredentialProvider())
        .overrideConfiguration(clientOverrideConfiguration())
        .build();
  }
}
